﻿namespace Refract.Navigation
{
    using System;
    using System.Collections.Generic;
    using System.Windows;
    using System.Windows.Controls;

    /// <summary>
    /// Implements region functionality
    /// </summary>
    public static class Region
    {
        #region Fields

        /// <summary>
        /// The region name dependency property
        /// </summary>
        public static readonly DependencyProperty NameProperty = 
            DependencyProperty.RegisterAttached("Name", typeof(string), typeof(FrameworkElement), null);

        private static Object _mutex = new Object();
        private static Dictionary<string, FrameworkElement> _regionList = new Dictionary<string, FrameworkElement>();

        #endregion Fields

        #region Properties

        public static IEnumerable<FrameworkElement> RegionList
        {
            get
            {
                lock (_mutex)
                {
                    return _regionList.Values;
                }
            }
        }

        #endregion Properties

        #region Methods

        /// <summary>
        /// Gets the name value from the dependency property.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <returns></returns>
        public static string GetName(FrameworkElement element)
        {
            return (string)element.GetValue(NameProperty);
        }

        /// <summary>
        /// Gets a region from the region list by name.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        public static UIElement GetRegion(string name)
        {
            lock (_mutex)
            {
                if (_regionList.ContainsKey(name))
                {
                    return _regionList[name];
                }

                return null;
            }
        }

        /// <summary>
        /// Sets the name value on the dependency property.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <param name="value">The value.</param>
        public static void SetName(FrameworkElement element, string value)
        {
            element.SetValue(NameProperty, value);
            SetRegion(value, element);
        }

        /// <summary>
        /// Sets a region by name in the region list.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="region">The region.</param>
        public static void SetRegion(string name, FrameworkElement region)
        {
            lock (_mutex)
            {
                _regionList[name] = region;
            }
        }

        #endregion Methods
    }
}